package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.enums.HuanXinMessageType;
import com.tanhua.dubbo.pojo.Question;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.server.vo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class TanHuaService {

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    @DubboReference(version = "1.0.0")
    private QuestionApi questionApi;

    @DubboReference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    public TodayBest queryUserInfo(Long userId) {
        //根据用户id查询用户的基本信息
        UserInfo userInfo = this.userInfoApi.queryByUserId(userId);
        TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setId(userInfo.getUserId());
        //得分
        todayBest.setFateValue(Convert.toLong(this.recommendUserApi.queryScore(userId, UserThreadLocal.get())));

        //记录访客
        this.visitorsApi.saveVisitor(userId, UserThreadLocal.get(), "个人主页");
        return todayBest;
    }

    public String queryQuestion(Long userId) {
        Question question = this.questionApi.queryQuestion(userId);
        if(null != question){
            //问题
            return question.getTxt();
        }
        return "你是谁？"; //默认问题
    }

    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    public void replyQuestion(Long userId, String reply) {
        //{"userId":1,"huanXinId":"HX_1","nickname":"黑马小妹","strangerQuestion":"你喜欢去看蔚蓝的大海还是去爬巍峨的高山？","reply":"我喜欢秋天的落叶，夏天的泉水，冬天的雪地，只要有你一切皆可~"}

        Long myUserId = UserThreadLocal.get();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", myUserId);
        map.put("huanXinId", "HX_" + myUserId);
        map.put("nickname", this.userInfoApi.queryByUserId(myUserId).getNickName());
        map.put("strangerQuestion", this.queryQuestion(userId));
        map.put("reply", reply);

        String msg = JSONUtil.toJsonStr(map);
        //发送消息
        this.huanXinApi.sendMsgFromAdmin("HX_" + userId, HuanXinMessageType.TXT, msg);
    }


}
